/* eslint newline-per-chained-call: 0 */
const del = require('del');
const g = require('gulp');
const $ = require('gulp-load-plugins')();
const u = require('./gulp.util');
const cfg = require('./config');
const {log, colors} = $.util;
const _ = require('lodash');

function zip_file_name(type) {
    const today = require('moment')().format('YYMMDD');
    return [cfg.name, type, today].join('-') + '.zip';
}

// 备份源码
g.task('src', () => {
    const fn = zip_file_name('src');
    log(colors.cyan(`zip ${fn} ...`));
    return u.src([
        u.dir([cfg.src.dir, cfg.dev.dir]),
        u.dir([cfg.src.dir, cfg.dev.dir], '.'),
        '.*', u.exclude(['.git/', '.svn/', '.idea/', '.vscode/']),
        '*.js', '*.json', '*.md', '*.txt',
        '!schema.*'
    ], {base: '..'})
        .pipe($.zip(fn))
        .pipe(g.dest('.'));
});

const {distDir, libsDir} = cfg;

// 清理发布
g.task('pub.clear', () => {
    const files = [
        `${distDir}/**`
    ];
    const args = u.getArgs();
    if (!_.includes(args, '-d')) {
        files.push(`!${distDir}`);
        files.push(`!${distDir}/${libsDir}/**`);
    }
    return del(files);
});

// 复制源码
g.task('pub.copy', ['pub.clear'], () => u.copyNew([
    u.dir([cfg.src.dir, cfg.dev.dir]),
    u.dir(cfg.src.dir, '.'),
    '*.js', '*.json', '.eslintignore'
], distDir, {base: '.'}));

// 发布打包
function zip(name) {
    const app = $.filter(
        u.dir(cfg.run.app.dir, '.js'),
        {restore: true}
    );

    const fn = zip_file_name(name || 'bin');
    log(colors.cyan(`zip ${fn} ...`));

    const files = [u.dir(cfg.run.dir)];
    const args = u.getArgs();
    if (_.includes(args, '-a')) {
        files.push(u.dir(libsDir));
    }
    const root = name ? `${cfg.name}-${name}` : cfg.name;
    return u.src(files, {base: '.'})
        .pipe(app).pipe($.uglify()).pipe(app.restore)
        .pipe($.rename(file => {
            let dir = file.dirname;
            if (dir.startsWith(cfg.run.dir)) {
                dir = '.' + dir.substr(cfg.run.dir.length);
            }
            file.dirname = `${root}/${dir}`;
        }))
        .pipe($.filter(file => file.path !== `${root}/${cfg.run.dir}`))
        .pipe($.zip(fn)).pipe(g.dest('../..'));
}

g.task('pub.zip', () => zip());
g.task('pub.app.zip', () => zip('app'));
